package com.shangyueshang.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.shangyueshang.common.SysConstants;
import com.shangyueshang.mapper.SupplierMapper;
import com.shangyueshang.model.Supplier;
import com.shangyueshang.request.PageReq;
import com.shangyueshang.response.HttpResult;
import com.shangyueshang.response.PageResult;
import com.shangyueshang.service.SupplierService;
import com.shangyueshang.utils.MyPageHelper;
import com.shangyueshang.utils.SecurityUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * @author JokeyFeng
 * @date: 2022/1/16 11:48
 * @project: shangyueshang
 * @package: com.shangyueshang.service.impl
 * @comment:
 */
@Slf4j
@Service
public class SupplierServiceImpl extends ServiceImpl<SupplierMapper, Supplier> implements SupplierService {
	
	@Override
	public HttpResult saveUpdate(Supplier supplier) {
		Supplier _supplier = super.getById(supplier.getId());
		if (_supplier == null) {
			supplier.setCreateTime(LocalDateTime.now());
			supplier.setCreator(SecurityUtil.getUsername());
		} else if (!_supplier.getName().equals(supplier.getName())) {
			_supplier = super.getOne(new QueryWrapper<Supplier>().eq(SysConstants.name, supplier.getName()));
			if (_supplier != null) {
				return HttpResult.fail("供应商名称已存在");
			}
		}
		supplier.setLastUpdateTime(LocalDateTime.now());
		supplier.setLastUpdator(SecurityUtil.getUsername());
		return HttpResult.ok(super.saveOrUpdate(supplier));
	}
	
	@Override
	public PageResult findPage(PageReq pageReq) {
		QueryWrapper<Supplier> queryWrapper = new QueryWrapper<>();
		queryWrapper.orderByDesc(SysConstants.create_time);
		pageReq.getLineParams().forEach(
				(k, v) -> {
					if (k.equals(SysConstants.name) || k.equals(SysConstants.main_products)) {
						queryWrapper.like(k, v);
					} else {
						queryWrapper.eq(k, v);
					}
				}
		);
		PageInfo<Supplier> pageInfo =
				PageHelper.startPage(
						pageReq.getPageNum(),
						pageReq.getPageSize()
				).doSelectPageInfo(
						() -> super.list(queryWrapper)
				);
		return MyPageHelper.getPageResult(pageInfo);
	}
}
